﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml.Linq;

namespace Microsoft.Office.OneNote
{
    internal abstract class OneNoteObjectStorageBase
    {
        public event EventHandler Updated;

        public int Count
        {
            get { return GetCollection().Count; }
        }

        public bool IsInvalid
        {
            get { return GetObjects().Any(o => o.IsInvalid); }
        }

        public bool HasConflicts
        {
            get { return GetObjects().Any(o => o.HasConflicts); } 
        }

        public void AcceptChanges()
        {
            foreach (var obj in GetObjects())
            {
                obj.AcceptChanges();
            }
        }

        public void RevertChanges()
        {
            foreach (var obj in GetObjects())
            {
                obj.RevertChanges();
            }
        }

        public void MarkInvalid()
        {
            foreach (var obj in GetObjects())
            {
                obj.MarkInvalid();
            }

            RaiseUpdated();
        }

        public void WriteTo(XContainer parent)
        {
            foreach (var child in GetObjects())
            {
                child.WriteTo(parent);
            }
        }

        public IEnumerable<T> OfType<T>() where T : OneNoteObject
        {
            return GetCollection().OfType<T>();
        }

        protected virtual ICollection GetCollection()
        {
            return new object[0];
        }

        protected void RaiseUpdated()
        {
            if (Updated != null)
            {
                Updated(this, EventArgs.Empty);
            }
        }

        private IEnumerable<OneNoteObject> GetObjects()
        {
            return GetCollection().Cast<OneNoteObject>();
        }
    }
}
